package com.fengkai.filepost.pdfoutstream.test;

import com.alibaba.druid.sql.visitor.functions.If;
import common.fengkai.filepost.entity.Seal;
import org.apache.commons.collections4.list.TreeList;
import org.checkerframework.checker.units.qual.A;
import org.junit.Test;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Solution {

    @Test
    public void testP () {
        Solution solution = new Solution();
        int[] nums = new int[]{3, 2, 4};
        int target = 6;
        int[] ints = solution.twoSum(nums, target);
        System.out.println(Arrays.toString(ints));

    }

    @Test
    //统计最后一个单词字数
    public void test01 () {
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        int count = 0;
        for (int i = s.length() - 1; i >= 0; i--) {
            if (s.charAt(i) == ' ') {
                break;

            }
            count++;
        }

        System.out.println(count);

    }

    @Test
    //统计一行字符串多少个指定字母
    public void test02 () {
        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        int j = 0;
        for (int i = 0; i <= s1.length() - 1; i++) {
            if (s2.equalsIgnoreCase(String.valueOf(s1.charAt(i)))) {
                j++;
            }
        }
        System.out.println(j);

    }

    @Test
    //生成了N个1到1000之间的随机整数（N≤1000），对于其中重复的数字，只保留一个，把其余相同的数去掉，不同的数对应着不同的学生的学号。然后再把这些数从小到大排序
    public void test03 () {

        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            int num = sc.nextInt();
            TreeSet set = new TreeSet();
            for (int i = 0; i <= num - 1; i++) {
                set.add(sc.nextInt());
            }

            set.stream().forEach(s -> {
                System.out.println(s);
            });
            //Iterator遍历效率远大于stream流
            Iterator iterator = set.iterator();
            while (iterator.hasNext()) {
                System.out.println(iterator.next());
            }

        }

    }

    @Test
    /**
     * •连续输入字符串，请按长度为8拆分每个字符串后输出到新的字符串数组；
     * •长度不是8整数倍的字符串请在后面补数字0，空字符串不处理。
     */
    public void test04 () {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s = sc.nextLine();
            if (s.length() % 8 != 0) {
                s += "00000000";
            }
            while (s.length() >= 8) {
                System.out.println(s.substring(0, 8));
                s = s.substring(8);
            }


        }
    }

    private static void makeString (String s) {
        if (s.length() < 8) {
            StringBuffer sb = new StringBuffer(s);
            while (true) {
                sb.append("0");
                if (sb.length() == 8) {
                    break;
                }
            }
            s = sb.toString();
            System.out.println(s);
        } else if (s.length() > 8) {
            String substring1 = s.substring(8, s.length());
            System.out.println("截取第8位后：" + substring1);
            String substring = s.substring(0, 8);
            System.out.println(substring);
            makeString(substring1);
        }

    }


    public int[] twoSum (int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();//元素值和元素位置的映射

        map.put(nums[0], 0);
        for (int i = 1; i < nums.length; i++) {
            int matchedNum = target - nums[i];//nums[i]和matchedNum的索引即为所求
            if (map.containsKey(matchedNum)) {//map存储过matchedNum的映射
                int index1 = i;
                int index2 = map.get(matchedNum);
                return new int[]{index1, index2};
            } else {//map未存储过
                map.put(nums[i], i);
            }
        }


        return null;
    }

    @Test
    /**
     * 求一个整数的所有质因子
     */
    public void test05 () {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            long num = sc.nextLong();
            long sqre = (long) Math.sqrt(num);
            for (long k = 2; k <= sqre; k++) {
                while (num % k == 0) {
                    System.out.print(k + " ");
                    num /= k;
                }
            }
            System.out.print(num == 1 ? "" : num + " ");
        }
    }

    @Test
    /**
     * 四舍五入
     */
    public void test06 () {
        Scanner sc = new Scanner(System.in);
        double v = sc.nextDouble();
        long round = Math.round(v);
        System.out.println(round);
    }

    @Test
    public void test07 () {
        String source = "auoengoianiuwbfanlsnkdwa";
        String target = "goai";

        char first = target.charAt(0);
        int sourcelength = source.length();
        int targetLength = target.length();
        int max = sourcelength - targetLength;
        for (int i = 0; i <= max; i++) {
            if (source.charAt(i) != first) {
                while (++i <= max && source.charAt(i) != first) ;
            }
            if (i <= max) {
                int j = i + 1;
                int end = j + targetLength - 1;
                for (int k = 1; j <= end && k <= targetLength - 1 && source.charAt(j)
                        == target.charAt(k); j++, k++)
                    ;

                if (j == end) {
                    System.out.println(i);
                    return;
                }
            }
        }
    }

    @Test
    public void test08 () {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入学生个数: ");
        int number = scan.nextInt();
        int[] score = new int[number];
        ArrayList<Integer> ints = new ArrayList<Integer>();
        for (int i = 0; i < score.length; i++) {
            System.out.println("输入第" + (i + 1) + "个  学生的成绩");
            score[i] = scan.nextInt();
        }
        int minScore = score[0];
//        for (int i = 0; i < score.length; i++) {
//            if (minScore > score[i]){
//                minScore = score[i];
//        }
//            }
        TreeSet<Integer> integers = new TreeSet<Integer>();
        for (int i = 0; i < score.length; i++) {
            integers.add(score[i]);
        }
        System.out.println("最小为" + integers.stream().findFirst());


    }

    @Test
    public void test09 () {
        int[] ints = {56, 89, 1};
        int minx = ints[0];
        for (int i = 0; i < ints.length; i++) {
            System.out.println(minx < ints[i]);
            if (minx > ints[i]) {
                minx = ints[i];
            }
        }

    }

    //    提示:
//            0 <= index <= 11111111
//            1 <= value <= 100000
//
//    输入描述：
//    先输入键值对的个数n（1 <= n <= 500）
//    然后输入成对的index和value值，以空格隔开
//
//    输出描述：
//    输出合并后的键值对（多行）
    @Test
    public void test10 () {
//        Scanner scanner = new Scanner(System.in);
//        ArrayList<Integer> input = new ArrayList<>();
//        int i = scanner.nextInt();
//        for (int j = 0; j < 2*i; j++) {
//            input.add(scanner.nextInt()) ;
//        }
//        HashMap<Integer, Integer> hashMap = new HashMap<>();
//        for (int j = 0; j < input.size() ; j+=2) {
//            Integer put = hashMap.put(input.get(j), input.get(j + 1));
//            if (put != null){
//                hashMap.put(input.get(j) , put + input.get(j+1));
//            }
//        }
//        TreeSet<Integer> integers = new TreeSet<>();
//        for (Integer integer : hashMap.keySet()) {
//            integers.add(integer);
//        }
//        input.removeAll(input);
//        for (Integer integer : integers) {
//            input.add(integer);
//            input.add(hashMap.get(integer));
//        }
//        for (int j = 0; j < input.size(); j++) {
//
//            if (!(j>=1 &&j%2!=0)){
//                System.out.print(input.get(j) + " ");
//
//            }else {
//                System.out.println(input.get(j));
//            }
//        }
        Scanner scanner = new Scanner(System.in);
        TreeMap<Integer, Integer> treeMap = new TreeMap<>();
        while (scanner.hasNext()) {
            int i = scanner.nextInt();
            for (int j = 0; j < i; j++) {
                int a = scanner.nextInt();
                int b = scanner.nextInt();
                treeMap.put(a, treeMap.getOrDefault(a, 0) + b);
            }

            for (Integer integer : treeMap.keySet()) {
                System.out.println(integer + " " + treeMap.get(integer));
            }
        }
    }

    //    写出一个程序，接受一个由字母、数字和空格组成的字符串，和一个字符，然后输出输入字符串中该字符的出现次数。（不区分大小写字母）
//    数据范围： 1 \le n \le 1000 \ 1≤n≤1000
//    输入描述：
//    第一行输入一个由字母和数字以及空格组成的字符串，第二行输入一个字符。
//    输出描述：
//    输出输入字符串中含有该字符的个数。（不区分大小写字母）
    @Test
    public void test11 () {
        Scanner sc = new Scanner(System.in);
        String s1 = sc.nextLine();
        String s2 = sc.nextLine();
        s1 = s1.toUpperCase();
        HashMap<String, Integer> characterIntegerHashMap = new HashMap<>();
        for (int i = 0; i < s1.length(); i++) {
            if (s2.equals(String.valueOf(s1.charAt(i)))) {
                characterIntegerHashMap.put(s2, characterIntegerHashMap.getOrDefault(s2, 0) + 1);
            }
        }
        int j = characterIntegerHashMap.get(s2) != null ? characterIntegerHashMap.get(s2) : 0;
        System.out.println(j);

    }

    //字符串自动补齐8位输出
    @Test
    public void test12 () {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String s = sc.nextLine();
            if (s.length() % 8 != 0) {
                s += "00000000";
            }
            while (s.length() >= 8) {
                System.out.println(s.substring(0, 8));
                s = s.substring(8);
            }
        }
    }

    //    功能:输入一个正整数，按照从小到大的顺序输出它的所有质因子（重复的也要列举）（如180的质因子为2 2 3 3 5 ）
    @Test
    public void test13 () {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            long num = sc.nextLong();
            long sqre = (long) Math.sqrt(num);
            for (long k = 2; k <= sqre; k++) {
                while (num % k == 0) {
                    System.out.print(k + " ");
                    num /= k;
                }
            }
            System.out.print(num == 1 ? "" : num + " ");
        }
    }

    //按照从右向左的阅读顺序，返回一个不含重复数字的新的整数
    @Test
    public void test14 () {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        StringBuffer out = new StringBuffer();
        HashMap<String, Integer> integerStringHashMap = new HashMap<>();
        for (int i = s.length() - 1; i >= 0; i--) {
            if (!integerStringHashMap.containsKey(String.valueOf(s.charAt(i)))) {
                integerStringHashMap.put(String.valueOf(s.charAt(i)), 0);
                out.append(String.valueOf(s.charAt(i)));
            }
        }
        System.out.println(out);
    }

    //编写一个函数，计算字符串中含有的不同字符的个数。字符在 ASCII 码范围内( 0~127 ，包括 0 和 127 )，换行表示结束符，不算在字符里。不在范围内的不作统计。多个相同的字符只计算一次
    //例如，对于字符串 abaca 而言，有 a、b、c 三种不同的字符，因此输出 3 。
    @Test
    public void test15 () {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        HashMap<Character, Integer> inputs = new HashMap<>();
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (!inputs.containsKey(s.charAt(i))) {
                inputs.put(s.charAt(i), 0);
                count++;
            }
        }
        System.out.println(count);
    }

    //输入一个 int 型的正整数，计算出该 int 型数据在内存中存储时 1 的个数。
    @Test
    public void test16 () {
        Scanner scanner = new Scanner(System.in);
        int s = scanner.nextInt();
        String i = Integer.toString(s, 2);
        System.out.println(i.length() - i.replaceAll("1", "").length());
    }

    /**
     * 输入描述：
     * 输入的第 1 行，为两个正整数，用一个空格隔开：N m
     * <p>
     * （其中 N （ <32000 ）表示总钱数， m （ <60 ）为希望购买物品的个数。）
     * <p>
     * 从第 2 行到第 m+1 行，第 j 行给出了编号为 j-1 的物品的基本数据，每行有 3 个非负整数 v p q
     * <p>
     * （其中 v 表示该物品的价格（ v<10000 ）， p 表示该物品的重要度（ 1 ~ 5 ）， q 表示该物品是主件还是附件。如果 q=0 ，
     * 表示该物品为主件，如果 q>0 ，表示该物品为附件， q 是所属主件的编号）
     * 输出描述：
     * 输出文件只有一个正整数，为不超过总钱数的物品的价格与重要度乘积的总和的最大值（ <200000 ）。
     * 示例1
     */
    @Test
    public void test17 () {
//        Scanner scanner = new Scanner(System.in);
//        String s = scanner.nextLine();
//        int N = s.charAt(0);
//        int m = s.charAt(2);
        String sh = "abc";
        System.out.println(sh.substring(0, 1));
        System.out.println(sh);
    }

    //统计范围内数字出现的次数  0-一千万
    @Test
    public void test18 () {
        System.out.println(countNum(1, 22, 2));
    }

    private int countNum (int L, int R, int x) {
        int count = 0;
        for (int i = L; i <= R; i++) {
            String s = String.valueOf(i);
            String replaceAll = s.replaceAll(String.valueOf(x), "");
            count += s.length() - replaceAll.length();
        }

        return count;
    }

    //判断一个字符串t是否可以由 “cm” 插入若干次到一个初始空字符串任意位置得到
    @Test
    public void test19 () {
        System.out.println(magicString("cmccmcmcmcmmccmmccccmccmcmccmmcmcccmmmmmmmm"));


    }

    private boolean magicString (String s) {
        if ("".equals(s)) {
            return true;
        }
        if (s.length() % 2 != 0) {
            return false;
        }
        if (s.replaceAll("c", "").length() != s.replaceAll("c", "").length()) {
            return false;
        }

        for (int i = 0; i < s.length() / 2 + 1; i++) {
            s = s.replaceAll("cm", "");
        }
        if ("".equals(s)) {
            return true;
        }

        return false;
    }


    //最远足迹
    @Test
    public void MaxFarthest () {
        //ferga13fdsf3(100,200)f2r3rfasf(300,400)
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        HashMap<Integer, String[]> integerHashMap = new HashMap<>();
        Integer max = 0;
        //正则提取括号内内容
        Pattern compile = Pattern.compile("\\((([^()]*))\\)");
        Matcher matcher = compile.matcher(input);
        while (matcher.find()) {
            String[] split = matcher.group(1).split(",");
            //剔除不合规的
            if (split[0].startsWith("0") || split[1].startsWith("0")) {
                continue;
            } else {
                //保存对应坐标
                integerHashMap.putIfAbsent(Integer.valueOf(split[0]) * Integer.valueOf(split[0]) + Integer.valueOf(split[1]) * Integer.valueOf(split[1]), split);
                max = Math.max(Integer.valueOf(split[0]) * Integer.valueOf(split[0]) + Integer.valueOf(split[1]) * Integer.valueOf(split[1]), max);
            }
        }
        if (integerHashMap.size() == 0) {
            System.out.println("(0,0)");
        } else {
            System.out.println("(" + integerHashMap.get(max)[0] + "," + integerHashMap.get(max)[1] + ")");
        }
    }

    @Test
    public void testRegix () {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        HashMap<Integer, String[]> integerHashMap = new HashMap<>();
        Integer max = 0;
        //正则提取括号内内容
        Pattern compile = Pattern.compile("\\(([^()]+),([^()]+)\\)");
        Matcher matcher = compile.matcher(input);
        while (matcher.find()) {
            System.out.println(matcher.group(1));
            System.out.println(matcher.group(2));
            System.out.println(matcher.group());
        }
    }

    @Test
    public void scoreSort () {
        //15
        //3,3,7,4,4,4,4,7,7,3,5,5,5,6,6
        //53,80,68,24,39,76,66,16,100,55,53,80,55,10,10
        Scanner scanner = new Scanner(System.in);
        Integer count = Integer.valueOf(scanner.nextLine());
        String[] firingOrder = scanner.nextLine().split(",");
        List<String> collect = Arrays.stream(firingOrder).collect(Collectors.toList());
        String[] socres = scanner.nextLine().split(",");

        //每个人得分情况
        HashMap<Integer, List<Integer>> idScoreCache = new HashMap<>();
        //最终每个人得分
        Map<Integer, Integer> idScoreMap = new HashMap<Integer, Integer>();

        for (int i = 0; i <= count - 1; i++) {
           if (idScoreCache.containsKey(Integer.valueOf(firingOrder[i]))){
               idScoreCache.get(Integer.valueOf(firingOrder[i])).add(Integer.valueOf(socres[i]));
           }else {
               ArrayList<Integer> integers = new ArrayList<>();
               integers.add(Integer.valueOf(socres[i]));
               idScoreCache.put(Integer.valueOf(firingOrder[i]), integers);
           }
        }

        for (Integer integer : idScoreCache.keySet()) {
            if (idScoreCache.get(integer).size() >= 3){
                //统计个人分数  要最高的三个分数之和
                List<Integer> integers = idScoreCache.get(integer).stream().sorted((v1, v2) -> v2.compareTo(v1)).collect(Collectors.toList()).subList(0, 3);
                idScoreMap.put(integer, integers.stream().reduce(Integer::sum).get());
            }
        }
        Integer[] out = idScoreMap.keySet().toArray(new Integer[idScoreMap.size()]);
        //冒泡排序
        for (int i = out.length - 1; i >= 0 ; i--) {
            for (int j = out.length - 1 ; j >= 1 ; j--) {
                if (idScoreMap.get(out[j]) > idScoreMap.get(out[j - 1])){
                    Integer tmp = out[j - 1];
                    out[j - 1] = out[j];
                    out[j] = tmp;
                }else if (Objects.equals(idScoreMap.get(out[j - 1]), idScoreMap.get(out[j]))){
                    if (out[j - 1] < out[j]){
                        Integer tmp = out[j - 1];
                        out[j - 1] = out[j];
                        out[j] = tmp;
                    }
                }
            }
        }
        StringBuffer stringBuffer = new StringBuffer();
        Arrays.stream(out).forEach( v -> {
            stringBuffer.append(v + ",");
        });
        stringBuffer.substring(0, stringBuffer.length() - 1);
        System.out.println(stringBuffer);

    }


    @Test
    public void testTreeList(){
        ArrayList<Integer> integers = new ArrayList<>();
        integers.add(15);
        integers.add(123);
        integers.add(1);
        integers.add(0);
        integers.add(-9);
        integers.add(123);
        integers.add(155123);
        integers.add(15123);
        integers.add(15334);
        integers.sort( (v1, v2) -> v2 .compareTo(v1));
        for (Integer integer : integers) {
            System.out.println(integer);
        }
    }

}
